<template>
  <div class="dashboard">
    <header class="mb-8">
      <h1 class="glow-text">系统仪表盘</h1>
      <div class="tech-line mt-2"></div>
    </header>

    <div class="dashboard-grid mb-8">
      <div class="stat-card">
        <div class="stat-label">活跃服务</div>
        <div class="stat-value">{{ serviceCount }}</div>
        <div class="flex items-center mt-2 text-sm">
          <span class="text-accent-blue">{{ serviceChangePercent }}%</span>
          <svg v-if="serviceChangePercent > 0" class="w-4 h-4 ml-1 text-accent-blue" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 10l7-7m0 0l7 7m-7-7v18"></path>
          </svg>
          <svg v-else-if="serviceChangePercent < 0" class="w-4 h-4 ml-1 text-accent-pink" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 14l-7 7m0 0l-7-7m7 7V3"></path>
          </svg>
          <span class="ml-1 text-light-dark">较上周</span>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-label">请求总数</div>
        <div class="stat-value">{{ requestCount }}</div>
        <div class="flex items-center mt-2 text-sm">
          <span class="text-accent-blue">{{ requestChangePercent }}%</span>
          <svg v-if="requestChangePercent > 0" class="w-4 h-4 ml-1 text-accent-blue" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 10l7-7m0 0l7 7m-7-7v18"></path>
          </svg>
          <svg v-else-if="requestChangePercent < 0" class="w-4 h-4 ml-1 text-accent-pink" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 14l-7 7m0 0l-7-7m7 7V3"></path>
          </svg>
          <span class="ml-1 text-light-dark">较昨日</span>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-label">错误率</div>
        <div class="stat-value">{{ errorRate }}%</div>
        <div class="flex items-center mt-2 text-sm">
          <span :class="errorRateChange < 0 ? 'text-accent-blue' : 'text-accent-pink'">{{ errorRateChange }}%</span>
          <svg v-if="errorRateChange < 0" class="w-4 h-4 ml-1 text-accent-blue" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 14l-7 7m0 0l-7-7m7 7V3"></path>
          </svg>
          <svg v-else-if="errorRateChange > 0" class="w-4 h-4 ml-1 text-accent-pink" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 10l7-7m0 0l7 7m-7-7v18"></path>
          </svg>
          <span class="ml-1 text-light-dark">较昨日</span>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-label">活跃故障注入</div>
        <div class="stat-value">{{ activeFaultCount }}</div>
        <div class="flex items-center mt-2 text-sm">
          <span class="text-accent-orange">{{ faultChangeCount }}</span>
          <span class="ml-1 text-light-dark">较昨日</span>
        </div>
      </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
      <div class="chart-container">
        <h3 class="text-lg font-medium mb-4">请求流量趋势</h3>
        <div class="h-full" ref="trafficChartRef"></div>
      </div>

      <div class="chart-container">
        <h3 class="text-lg font-medium mb-4">响应时间分布</h3>
        <div class="h-full" ref="responseTimeChartRef"></div>
      </div>
    </div>

    <div class="card">
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-medium">最近请求</h3>
        <router-link to="/traces" class="btn btn-outline text-sm">查看全部</router-link>
      </div>

      <div class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="border-b border-dark-light">
              <th class="py-2 px-4 text-left">服务</th>
              <th class="py-2 px-4 text-left">路径</th>
              <th class="py-2 px-4 text-left">方法</th>
              <th class="py-2 px-4 text-left">状态码</th>
              <th class="py-2 px-4 text-left">响应时间</th>
              <th class="py-2 px-4 text-left">时间</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="trace in recentTraces" :key="trace.id" class="border-b border-dark-light hover:bg-dark-darker">
              <td class="py-2 px-4">{{ trace.serviceName }}</td>
              <td class="py-2 px-4 font-mono text-sm">{{ trace.path }}</td>
              <td class="py-2 px-4">
                <span :class="{
                  'badge badge-blue': trace.method === 'GET',
                  'badge badge-green': trace.method === 'POST',
                  'badge badge-purple': trace.method === 'PUT',
                  'badge badge-orange': trace.method === 'DELETE',
                  'badge badge-yellow': !['GET', 'POST', 'PUT', 'DELETE'].includes(trace.method)
                }">{{ trace.method }}</span>
              </td>
              <td class="py-2 px-4">
                <span :class="{
                  'text-accent-blue': trace.statusCode < 300,
                  'text-accent-yellow': trace.statusCode >= 300 && trace.statusCode < 400,
                  'text-accent-orange': trace.statusCode >= 400 && trace.statusCode < 500,
                  'text-accent-pink': trace.statusCode >= 500
                }">{{ trace.statusCode }}</span>
              </td>
              <td class="py-2 px-4">{{ trace.duration.toFixed(2) }} ms</td>
              <td class="py-2 px-4 text-light-dark">{{ formatTime(trace.timestamp) }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useServicesStore } from '../stores/services';
import { useTracesStore } from '../stores/traces';
import { useFaultsStore } from '../stores/faults';

// 引入状态管理
const servicesStore = useServicesStore();
const tracesStore = useTracesStore();
const faultsStore = useFaultsStore();

// 图表引用
const trafficChartRef = ref<HTMLElement | null>(null);
const responseTimeChartRef = ref<HTMLElement | null>(null);

// 模拟数据
const serviceCount = ref(12);
const serviceChangePercent = ref(8.5);
const requestCount = ref(24689);
const requestChangePercent = ref(12.3);
const errorRate = ref(1.2);
const errorRateChange = ref(-0.5);
const activeFaultCount = ref(3);
const faultChangeCount = ref('+1');

// 最近请求数据
const recentTraces = ref([
  {
    id: '1',
    serviceId: '1',
    serviceName: 'user-service',
    method: 'GET',
    path: '/api/users/123',
    statusCode: 200,
    duration: 45.2,
    timestamp: new Date(Date.now() - 120000).toISOString()
  },
  {
    id: '2',
    serviceId: '2',
    serviceName: 'order-service',
    method: 'POST',
    path: '/api/orders',
    statusCode: 201,
    duration: 78.5,
    timestamp: new Date(Date.now() - 180000).toISOString()
  },
  {
    id: '3',
    serviceId: '3',
    serviceName: 'payment-service',
    method: 'PUT',
    path: '/api/payments/456',
    statusCode: 204,
    duration: 32.1,
    timestamp: new Date(Date.now() - 240000).toISOString()
  },
  {
    id: '4',
    serviceId: '1',
    serviceName: 'user-service',
    method: 'DELETE',
    path: '/api/users/789',
    statusCode: 404,
    duration: 12.8,
    timestamp: new Date(Date.now() - 300000).toISOString()
  },
  {
    id: '5',
    serviceId: '2',
    serviceName: 'order-service',
    method: 'GET',
    path: '/api/orders/status',
    statusCode: 500,
    duration: 156.3,
    timestamp: new Date(Date.now() - 360000).toISOString()
  }
]);

// 格式化时间
const formatTime = (timestamp: string) => {
  const date = new Date(timestamp);
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
};

// 图表相关代码已简化

// 获取数据
const fetchData = async () => {
  try {
    await Promise.all([
      servicesStore.fetchServices(),
      tracesStore.fetchTraces(),
      faultsStore.fetchFaults(),
    ]);

    // 更新统计数据
    // const stats = await systemApi.getStats();
    // 这里可以用实际数据替换模拟数据
  } catch (error) {
    console.error('获取仪表盘数据失败:', error);
  }
};

// 生命周期钩子
onMounted(() => {
  fetchData();

  // 设置定时刷新
  const refreshInterval = setInterval(fetchData, 30000);

  // 清理定时器
  const cleanup = () => {
    clearInterval(refreshInterval);
  };

  // 组件卸载时清理
  return cleanup;
});
</script>

<style scoped>
/* 可以添加组件特定的样式 */
</style>
